﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Extensions;

namespace ERPStore.NewsLetters.Services
{
	public class ExternalRecipientSourceProvider : IEmailListSourceProvider
	{
		private Models.ExternalEmailListSource m_Settings;
		private Models.EmailListSource m_Source;

		public ExternalRecipientSourceProvider(NewsLettersService newsLetterService)
		{
			this.NewsLetterService = newsLetterService;
		}

		protected NewsLettersService NewsLetterService { get; private set; }

		#region IEmailListSourceProvider Members

		public string SourceTypeId
		{
			get { return "5343ADAC-CCB5-427B-9F90-ACA934C0EF69"; }
		}

		public string DisplayName
		{
			get { return "Source externe"; }
		}

		public void Initialize(Models.EmailListSource source)
		{
			m_Source = source;

			if (source.Settings.IsNullOrEmpty())
			{
				m_Settings = new Models.ExternalEmailListSource();
			}
			else
			{
				var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Models.ExternalEmailListSource));
				var buffer = System.Text.Encoding.UTF8.GetBytes(source.Settings);
				using (var ms = new System.IO.MemoryStream(buffer))
				{
					m_Settings = (Models.ExternalEmailListSource)serializer.Deserialize(ms);
					ms.Flush();
					ms.Close();
				}
			}
		}

		public IEnumerable<Models.EmailRecipient> GetList(int pageIndex, int pageSize, out int count)
		{
			var list = NewsLetterService.GetEmailRecipientListByEmailListSource(m_Source.Id, pageIndex, pageSize, out count);
			return list;
		}

		public IList<ERPStore.Models.BrokenRule> Validate()
		{
			return null;
		}

		public string GetSerializedSettings()
		{
			return m_Settings.SerializeToXml();
		}

		#endregion
	}
}
